
const MgTool = require('./tool');

let mysql = require('mysql');
exports.update = (_table_name, params, updatekey) => {
    let sqlStr = "update " + _table_name + " set";
    if (params) {
        sqlStr = MgTool.paramsSplicing(sqlStr, params, ',');
    }
    if (updatekey) {
        sqlStr += " where";
        sqlStr = MgTool.paramsSplicing(sqlStr, updatekey, ',');
    }
    return sqlStr;
}

exports.find = (_table_name, params) => {
    let sqlStr = "select * from " + _table_name;

    if (params) {
        sqlStr += " where";
        sqlStr = MgTool.paramsSplicing(sqlStr, params, 'and');
    }
    return sqlStr;
}

exports.findCondition = (sql, params) => {
    let sqlStr = sql;
    if (params) {
        sqlStr = MgTool.paramsSplicing(sqlStr, params, 'and');
    }
    return sqlStr;
}

exports.delete = (_table_name, params) => {
    let sqlStr = "delete from " + _table_name;

    if (params) {
        sqlStr += " where";
        sqlStr = MgTool.paramsSplicing(sqlStr, params, 'and');
    }
    return sqlStr
}

exports.add = (_table_name, params) => {
    let sqlStr = "insert into " + _table_name + " ";
    if (params) {
        let keyStr = "(",
            valStr = "(";

        for (let key in params) {
            keyStr += key + ",";
            valStr +=  mysql.escape(params[key]) + ",";
        }

        keyStr = keyStr.substring(0, keyStr.length - 1) + ")";
        valStr = valStr.substring(0, valStr.length - 1) + ")";

        sqlStr += keyStr + " values " + valStr;
    }
    return sqlStr
}